package com.leha.utils;


import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by Justin on 2014/11/14.
 */
public class TimeDifferenceTool {

    public static final String formatDate(Date date, String formatStyle) {
        SimpleDateFormat sdf = new SimpleDateFormat(formatStyle);
        String nowDate = sdf.format(date);
        return nowDate;
    }

    public static String showDateString(Date date) {
        if (date == null) {
            return new String();
        }
        String result;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        try {
            calendar1.setTime(df.parse(formatDate(date, "yyyy-MM-dd HH:mm:ss.SSS")));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        calendar2.setTime(new Date());
        if (calendar2.get(Calendar.YEAR) > calendar1.get(Calendar.YEAR)) {
            result = (calendar2.get(Calendar.YEAR) - calendar1.get(Calendar.YEAR)) + "年前";
        } else if (calendar2.get(Calendar.MONTH) > calendar1.get(Calendar.MONTH)) {
            result = (calendar2.get(Calendar.MONTH) - calendar1.get(Calendar.MONTH)) + "月前";
        } else if (calendar2.get(Calendar.DAY_OF_MONTH) > calendar1.get(Calendar.DAY_OF_MONTH)) {
            result = (calendar2.get(Calendar.DAY_OF_MONTH) - calendar1.get(Calendar.DAY_OF_MONTH)) + "天前";
        } else if (calendar2.get(Calendar.HOUR_OF_DAY) > calendar1.get(Calendar.HOUR_OF_DAY)) {
            result = (calendar2.get(Calendar.HOUR_OF_DAY) - calendar1.get(Calendar.HOUR_OF_DAY)) + "小时前";
        } else if (calendar2.get(Calendar.MINUTE) > calendar1.get(Calendar.MINUTE)) {
            result = (calendar2.get(Calendar.MINUTE) - calendar1.get(Calendar.MINUTE)) + "分钟前";
        } else if (calendar2.get(Calendar.SECOND) > calendar1.get(Calendar.SECOND)) {
            result = "刚刚";
        } else {
            result = "刚刚";
        }
        return result;
    }

    public static void main(String args[]) {
        Date date = TimestampUtil.now();
        System.err.println(showDateString(new Timestamp(System.currentTimeMillis() - 8000000)));
    }
}
